package com.ruoyi.task;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.domain.AdvMembers;
import com.ruoyi.domain.AdvOrders;
import com.ruoyi.enums.OrderStatusEnum;
import com.ruoyi.mapper.AdvMembersMapper;
import com.ruoyi.mapper.AdvOrdersMapper;
import com.ruoyi.service.WxAppService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class WxappTask {

    @Autowired
    private AdvOrdersMapper advOrdersMapper;

    @Autowired
    private WxAppService wxAppService;

    @Autowired
    private AdvMembersMapper advMembersMapper;

    //    @Scheduled(cron = "0 0/2 * * * ?")
    public void sendGoods() throws IOException {
        // 当前时间减去2天
        LocalDateTime sevenDaysAgo = LocalDateTime.now().minusDays(2);

        // 查询已支付但是没发货的订单
        List<AdvOrders> orders = advOrdersMapper.
                findOrdersByPayButNotSendGoods(OrderStatusEnum.SUCCESS.getType(), sevenDaysAgo);

        /**
         * 调用微信小程序发货接口进行发货
         */
        for (AdvOrders order : orders) {
            AdvMembers advMembers = advMembersMapper.selectAdvMembersByAdvMembersId(order.getAdvMembersId());
            Map<String, String> result = wxAppService.deliverGoods(order.getOrdersno(), advMembers.getWeOpenid());
            log.info("订单编号: {" + order.getOrdersno() + "} 长时间未发货, " +
                    "已进行自动发货, 发货结果: {" + " }" + JSONObject.toJSONString(result));
        }
    }

}
